# coding: UTF-8
from urllib.request import urlopen
from urllib.error import *
from urllib.parse import quote, unquote
import time
import json
from pypinyin import pinyin, lazy_pinyin
from sys import argv


def legacy_api(provice, city, counties):
    try:
        province_api = urlopen("http://www.weather.com.cn/data/city3jdata/china.html")
    except HTTPError as e:
        time.sleep(5)
        province_api = urlopen("http://www.weather.com.cn/data/city3jdata/china.html")

    province_dict = json.loads(province_api.read().decode("utf-8"))
    province_order = list(province_dict.keys())[0]    # 第一个值作为默认值
    for k, v in province_dict.items():
        if v == provice:    # Todo:省份作为参数
            province_order = k
            break

    city_api = urlopen("http://www.weather.com.cn/data/city3jdata/provshi/{}.html".format(province_order))
    city_dict = json.loads(city_api.read().decode("utf-8"))
    city_order = list(city_dict.keys())[0]
    for k, v in city_dict.items():
        if v == city:    # Todo:城市作为参数
            city_order = k

    counties_api = urlopen("http://www.weather.com.cn/data/city3jdata/station/{}.html".format(province_order+city_order))
    counties_dict = json.loads(counties_api.read().decode("utf8"))
    counties_order = list(counties_dict.keys())[0]
    for k, v in counties_dict.items():
        if v == counties:    # Todo:区域作为参数
            counties_order = k

    target = urlopen("http://www.weather.com.cn/data/cityinfo/{}.html".format(province_order+city_order+counties_order))

    target_dict = json.loads(target.read().decode("utf8"))
    print(province_order + city_order + counties_order)
    print(province_dict[province_order], city_dict[city_order], counties_dict[counties_order])
    print(target_dict.get("weatherinfo").get("temp1")+"-"+target_dict.get("weatherinfo").get("temp2"))
    print(target_dict.get("weatherinfo").get("weather"))


def juhe_weather_api(city_name):
    """聚合数据api"""
    try:
        api_res = urlopen("http://v.juhe.cn/weather/index?format=2&cityname={}&dtype=json&key={}".format(quote(city_name), "8d188b7e3d93025c5d1735c50ec793d7"))
    except HTTPError as e:
        time.sleep(5)
        api_res = urlopen(
            "http://v.juhe.cn/weather/index?format=2&cityname={}&dtype=json&key={}".format(quote(city_name),
                                                                                           "8d188b7e3d93025c5d1735c50ec793d7"))
    weather_dict = json.loads(api_res.read().decode("utf-8"))
    # print("聚合数据api信息:")
    # print("城市:", weather_dict["result"]["today"]["city"])
    # # print("一天温度:", weather_dict["result"]["today"]["temperature"])
    # print("温度:", weather_dict["result"]["sk"]["temp"])
    #
    # print(weather_dict["result"]["today"]["weather"])
    # print("日期:", weather_dict["result"]["today"]["date_y"])
    if weather_dict["result"] is None:
        return ""
    else:
        return weather_dict["result"]["today"]["city"]+" "+weather_dict["result"]["sk"]["temp"]+" "+ \
               weather_dict["result"]["today"]["weather"]+" "+weather_dict["result"]["today"]["date_y"]


def xinzhi_weather_api(city_name):
    """心知天气api"""
    try:
        url = "https://api.seniverse.com/v3/weather/hourly.json?key={}&location={}&language=zh-Hans&unit=c&start=0&hours=1".format(
                                                                                           "SsxbSX2vCZylVaOO2",
                                                                                            "".join(lazy_pinyin(city_name)))
        api_res = urlopen(
            "https://api.seniverse.com/v3/weather/hourly.json?key={}&location={}&language=zh-Hans&unit=c&start=0&hours=1".format(
                                                                                           "SsxbSX2vCZylVaOO2",
                                                                                            "".join(lazy_pinyin(city_name))))

    except HTTPError as e:  # Todo:处理200和404状态码同时返回的问题
        time.sleep(5)
        api_res = urlopen(
            "https://api.seniverse.com/v3/weather/hourly.json?key={}&location={}&language=zh-Hans&unit=c&start=0&hours=1".format(
                                                                                            "SsxbSX2vCZylVaOO2",
                                                                                             "".join(lazy_pinyin(city_name))))

    weather_dict = json.loads(api_res.read().decode("utf-8"))
    # print("心知天气api信息:")
    # print("城市:", weather_dict["results"][0]["location"]["name"])
    # print("当前温度:", weather_dict["results"][0]["hourly"][0]["temperature"])
    # print(weather_dict["results"][0]["hourly"][0]["text"])
    # print("日期:", weather_dict["results"][0]["hourly"][0]["time"])
    try:
        if weather_dict["status_code"] == "AP010001":
            return ""
    except KeyError as e:
        return weather_dict["results"][0]["location"]["name"]+" "+weather_dict["results"][0]["hourly"][0]["temperature"]+" "+ \
            weather_dict["results"][0]["hourly"][0]["text"] + " " + weather_dict["results"][0]["hourly"][0]["time"]


def tianqi_weather_api(city_name):
    """全球天气api"""
    try:
        api_res = urlopen(
            "https://www.tianqiapi.com/api/?version=v6&city={}".format(quote(city_name)))

    except HTTPError as e:
        time.sleep(5)
        api_res = urlopen(
            "https://www.tianqiapi.com/api/?version=v6&city={}".format(quote(city_name)))

    weather_dict = json.loads(api_res.read().decode("utf-8"))
    # print("全球天气api信息:")
    # print("城市:", weather_dict["city"])
    # print("日期:", weather_dict["date"], weather_dict["wea"])
    # print("当前温度:", weather_dict["tem"])
    # print(weather_dict["air_tips"])
    return weather_dict["city"]+" "+weather_dict["tem"]+" "+weather_dict["wea"]+" "+weather_dict["date"]


if __name__ == '__main__':
    arg1 = argv[1]
    arg2 = argv[2]
    # Chinese API
    if arg1 == "juhe":
        print(juhe_weather_api(arg2))
    elif arg1 == "xinzhi":
        print(xinzhi_weather_api(arg2))
    elif arg1 == "global":
        print(tianqi_weather_api(arg2))
    else:
        print(juhe_weather_api(arg2))
        print(xinzhi_weather_api(arg2))
        print(tianqi_weather_api(arg2))









